iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 25
0
Software Development

python 自學系列 第 25

python day25(flask)

  • 分享至 

  • xImage
  •  

flask 是一個 WSGI (Web Server Gateway Interface) 輕量級的 Web 框架.可以參考 Flask 內容.使用 pip3 (使用的是 python3)下載安裝 flask

> pip3 install -U Flask
Collecting Flask
  Using cached https://files.pythonhosted.org/packages/9b/93/628509b8d5dc749656a9641f4caf13540e2cdec85276964ff8f43bbb1d3b/Flask-1.1.1-py2.py3-none-any.whl
Collecting Jinja2>=2.10.1 (from Flask)
  Using cached https://files.pythonhosted.org/packages/65/e0/eb35e762802015cab1ccee04e8a277b03f1d8e53da3ec3106882ec42558b/Jinja2-2.10.3-py2.py3-none-any.whl
Collecting Werkzeug>=0.15 (from Flask)
  Using cached https://files.pythonhosted.org/packages/ce/42/3aeda98f96e85fd26180534d36570e4d18108d62ae36f87694b476b83d6f/Werkzeug-0.16.0-py2.py3-none-any.whl
Collecting click>=5.1 (from Flask)
  Using cached https://files.pythonhosted.org/packages/fa/37/45185cb5abbc30d7257104c434fe0b07e5a195a6847506c074527aa599ec/Click-7.0-py2.py3-none-any.whl
Collecting itsdangerous>=0.24 (from Flask)
  Using cached https://files.pythonhosted.org/packages/76/ae/44b03b253d6fade317f32c24d100b3b35c2239807046a4c953c7b89fa49e/itsdangerous-1.1.0-py2.py3-none-any.whl
Collecting MarkupSafe>=0.23 (from Jinja2>=2.10.1->Flask)
  Downloading https://files.pythonhosted.org/packages/ce/c6/f000f1af136ef74e4a95e33785921c73595c5390403f102e9b231b065b7a/MarkupSafe-1.1.1-cp37-cp37m-macosx_10_6_intel.whl
Installing collected packages: MarkupSafe, Jinja2, Werkzeug, click, itsdangerous, Flask
Successfully installed Flask-1.1.1 Jinja2-2.10.3 MarkupSafe-1.1.1 Werkzeug-0.16.0 click-7.0 itsdangerous-1.1.0
You are using pip version 19.0.3, however version 19.2.3 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

下載好之後,建立一個 hello.py,__name__代表目前執行的模組,@app.route('/') 是 python 的 decorator.表示輸入網址的根目錄會導到 hello 這 function.

from flask import Flask, escape, request

app = Flask(__name__)

@app.route('/')
def hello():
    name = request.args.get("name", "World")
    return f'Hello, {escape(name)}!'

接著透過下列指令就可以跑起來一個 web server.

 > env FLASK_APP=hello.py flask run
 * Serving Flask app "hello.py"
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [05/Oct/2019 17:53:38] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [05/Oct/2019 17:53:38] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [05/Oct/2019 17:53:40] "GET / HTTP/1.1" 200 -

在網頁輸入 http://localhost:5000/ 就可以看到 Hello, World!

http request GET

@app.route('/sayHello' , methods=['GET'])
def sayHello():
    name = request.args.get('name')
    return 'Hello {}'.format(name)

在網頁輸入http://localhost:5000/sayHello?name=Daniel就可以看到 Hello Daniel

http request POST

建立一個 function sumNumber(),透過request.values取的參數 num1 和 num2 然後做加總.

@app.route('/sumNumber' , methods=['POST'])
def sumNumber():
    num1 = request.values['num1']
    num2 = request.values['num2']
    return str(int(num1) + int(num2))

回傳不能是 int 要是 string 的型態,不然會出現下面錯誤.

TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a int.

接著使用之前的 urllib 模組方式,用 post 的方式呼叫 sumNumber,得到回傳值 3.

>>> from urllib import request, parse
>>> parms = {'num1':1 , 'num2':2}
>>> post_data = parse.urlencode(parms)
>>> post_data = post_data.encode('ascii')
>>> req_obj = request.Request('http://127.0.0.1:5000/sumNumber', post_data)
>>> with request.urlopen(req_obj) as res_obj:
...  print(res_obj.read())
...
b'3'

上一篇
python day24(airflow)
下一篇
python day26(crawler)
系列文
python 自學30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言